package tetris;
// <editor-fold defaultstate="collapsed" desc="import">
import main.Main;
import java.awt.*;
import java.io.*;
import java.net.Socket;
import java.util.Hashtable;
import javax.swing.*;// </editor-fold>
public class Tetris extends javax.swing.JFrame {
    // <editor-fold defaultstate="collapsed" desc="Variable declaration">

    public JFrame frame;
    public Board board;
    public String username;
    public static Main main;
    public JLabel player1;
    public JLabel player2;
    public String[] userList;
    public int userListIndex = 0;
    private JPanel Panel;
    Hashtable<String, Integer> bangdiem;
    private Socket skt;
    public BufferedReader in;
    public PrintWriter out;
    public static String host = main.host;
    public static int port = main.port;
    int numberOfUserLose = 0;
    // </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Tetris()">

    public Tetris() {
        // <editor-fold defaultstate="collapsed" desc="initComponent()">
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
        }
        Panel = new JPanel();
        board = new Board(this);
        player1 = new JLabel();
        player1.setFont(new java.awt.Font("Tahoma", 1, 14));
        player1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        player1.setForeground(Color.WHITE);
        player1.setText("demo: DBName=tetris, 'root',pass=''");
        player2 = new JLabel();
        player2.setFont(new java.awt.Font("Tahoma", 1, 14));
        player2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        player2.setForeground(Color.WHITE);
        player2.setText("Player 2");
        
        JPanel playerPanel1 = new JPanel();
        playerPanel1.setBackground(new Color(153,51,0));
        playerPanel1.setBounds(5, 650, 345, 25);
        playerPanel1.add(player1);
        Panel.add(playerPanel1);
        JPanel playerPanel2 = new JPanel();
        playerPanel2.setBackground(new Color(153,51,0));
        playerPanel2.setBounds(600, 650, 345, 25);
        playerPanel2.add(player2);
        Panel.add(playerPanel2);
        
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Tetris");
        setPreferredSize(new java.awt.Dimension(960, 715));
        setResizable(false);
        getContentPane().setLayout(null);
        getContentPane().add(Panel);

        Panel.setBackground(new java.awt.Color(0, 0, 0));
        Panel.setForeground(new java.awt.Color(255, 255, 255));
        Panel.setLayout(null);
        Panel.setBounds(0, 0, 960, 685);
        Panel.add(board);
        board.setBounds(0, 0, 960, 650);
        pack();
        setLocationRelativeTo(null);// </editor-fold>
        bangdiem = new Hashtable<String, Integer>();


    }// </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Tetris(Main main, int i)">
    public Tetris(Main main, int i, String user) {
        this();
        this.username = user;
        userList = new String[10];
        userListIndex = 0;
        userList[userListIndex++] = username;
        bangdiem.put(userList[userListIndex - 1], 0);
        player1.setText(username);
        board.listUserField.setText(username);
        board.highScoreScroll.setVisible(false);
        board.listUserField.setBounds(18, 350, 205, 200);
        this.main = main;
        if (i == 1)// neu la may chu
        {
            setTitle("Tetris-Multi");
            board.startButton.setText("start room");
            board.pauseButton.setText("Pause/Resume");
            board.statusField.setText("click START to begin new game");
            board.exitButton.setText("Back");
            board.loginButton.setVisible(false);

        } else {//neu la may khach
            setTitle("Tetris-Multi");
            board.startButton.setVisible(false);
            board.pauseButton.setText("Pause/Resume");
            board.statusField.setText("please wait for game");
            board.exitButton.setText("Back");
            board.loginButton.setVisible(false);
        }
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Tetris(Main main, int i, String user)">
    /*
     public Tetris(Main main, int i, String user) {
     this(main, i);
     this.username = user;
     }*/// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="main(String args[])">
    /*
     public static void main(String args[]) {
     java.awt.EventQueue.invokeLater(new Runnable() {
     public void run() {
     Tetris tetris = new Tetris();
     tetris.setVisible(true);
     }
     });
     }*/// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="setlistuser(String list)">

    public void setlistuser(String newUser) {
        //userList = new String[10];
        //userListIndex = 0;
        char[] s = newUser.toCharArray();
        int j = 0;
        for (int i = 0; i < newUser.length(); i++) {
            if (s[i] == '|') {
                newUser = newUser.substring(j, i);
                userList[userListIndex++] = newUser;
                player2.setText(newUser);
                bangdiem.put(userList[userListIndex - 1], 0);
                j = ++i;
            }
        }
        if (j == 0) {
            userList[userListIndex++] = newUser;
            player2.setText(newUser);
            bangdiem.put(userList[userListIndex - 1], 0);
        }
        String str = "";
        for (int i = 0; i < userListIndex; i++) {
            str = str + userList[i].toString() + ": " + bangdiem.get(userList[i]) + "\n";
        }
        //board.listUserField.setFont(new java.awt.Font("Tahoma", 1, 14));
        board.listUserField.setText(str);
        System.out.println("client da nhan duoc danh sach cac user: " + str);
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="startgame()">

    public void startgame() {
        board.start();
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="pausegame()">

    public void pausegame() {
        board.pause();
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="denhlen(int diem, String from)">

    public void denhlen(int diem, String from) {
        System.out.println("start Denh len");
        for (int i = 0; i < diem; i++) {
            board.addALine();
        }
        int diemhientai = bangdiem.get(from);
        diem = board.addscore1(diem);
        diemhientai = diemhientai + diem;
        bangdiem.remove(from);
        bangdiem.put(from, diemhientai);
        String str = "";
        for (int i = 0; i < userListIndex; i++) {
            str = str + userList[i].toString() + ": " + bangdiem.get(userList[i]) + "\n";
        }
        board.listUserField.setText(str);
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="ghidiem(int diem)">

    public void ghidiem(int diem) {
        main.sendghidiem(diem);
        int diemhientai = bangdiem.get(username);
        diem = board.addscore1(diem);
        diemhientai = diemhientai + diem;
        bangdiem.remove(username);
        bangdiem.put(username, diemhientai);
        String str = "";
        for (int i = 0; i < userListIndex; i++) {
            str = str + userList[i].toString() + ": " + bangdiem.get(userList[i]) + "\n";
        }
        board.listUserField.setText(str);
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="getscorefromserver()">

    public void getscorefromserver() {
        board.highScoreField.setText("");
        try {
            skt = new Socket(host, port);
            PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
            out.println("4|" + username);
            String input = in.readLine();
            //System.out.println(input);
            char[] input2 = input.toCharArray();
            int i = 0;
            for (int j = 0; j < input2.length; j++) {
                if (input2[j] == '|') {
                    String sscore = input.substring(i, j);
                    i = ++j;
                    for (; j < input2.length; j++) {
                        if (input2[j] == '|') {
                            String date = input.substring(i, j);
                            i = ++j;
                            board.highScoreField.setText(board.highScoreField.getText() + "\n" + sscore + "\t" + date);
                            break;
                        }
                    }
                }
            }

        } catch (Exception e) {
            System.err.print(e);
        }
    }
// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="ghidiemlenserver()">

    public void ghidiemlenserver(int diem) {
        try {
            skt = new Socket(host, port);
            PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
            out.println("5|" + username + "|" + diem);
        } catch (Exception e) {
            System.err.print(e);
        }
    }
// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="logout()">
//thoat session()

    public void logout() {
        try {
            skt = new Socket(host, port);
            in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
            out = new PrintWriter(skt.getOutputStream(), true);
            out.println("2|" + username);
            System.exit(-1);
        } catch (Exception e) {
            System.err.println(e);
        }
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="deleteuser">

    public void deleteuser(String name) {

        for (int i = 0; i < userListIndex; i++) {
            if (userList[i] != null && userList[i].equals(name)) {
                //userList[i] = " ";
                for(int e = i;e<userListIndex-1;e++){
                    userList[e]=userList[e+1];
                }
                userListIndex--;
            }
        }
        String str = "";
        for (int i = 0; i < userListIndex; i++) {
            str = str + userList[i].toString() + ": " + bangdiem.get(userList[i]) + "\n";
        }
        board.listUserField.setText(str);
        //numberofuserlose++;
        if (numberOfUserLose == userListIndex - 1 && board.isStarted) {
            board.timer.stop();
            board.statusField.setText("Ban da chien thang");
            board.isStarted = false;
        }

    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="haveusergameover">

    public void haveusergameover(String name) {

        for (int i = 0; i < userListIndex; i++) {
            if (userList[i] != null && userList[i].equals(name)) {
                int diem = bangdiem.get(userList[i]);
                bangdiem.remove(userList[i]);
                userList[i] = userList[i] + ": GAME OVER";
                bangdiem.put(userList[i], diem);
            }
        }
        String str = "";
        for (int i = 0; i < userListIndex; i++) {
            str = str + userList[i].toString() + ": " + bangdiem.get(userList[i]) + "\n";
        }
        board.listUserField.setText(str);
        numberOfUserLose++;
        if (numberOfUserLose == userListIndex - 1 && board.isStarted) {
            board.pause();
            board.statusField.setText("Bạn đã chiến thắng");
            //JOptionPane.showMessageDialog(null, "Ban da chien thang");

        }

    } // </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="gameover()">

    public void gameover() {
        main.sendgameover();
        //JOptionPane.showMessageDialog(null, "Ban da thua cuoc");
        board.statusField.setText("Bạn đã thua");
    }// </editor-fold>
    // <editor-fold defaultstate="collapsed" desc="recPosition(String str)">
    public void recPosition(String str) {
        String a[] = new String[4];
        try {
            for (int e = 0; e < 4; e++) {
                char[] s = str.toCharArray();
                int i = 0;
                while (s[i] != '|') {
                    i++;
                }

                a[e] = str.substring(0, i);
                str = str.substring(i + 1);
                //a[e] = i;
            }
        } catch (Exception e) {
        }
        a[3] = str;
        String username2 = a[0];
        String curX2 = a[1];
        String curY2 = a[2];
        String shapeOrder2 = a[3];
        board.curX2 = Integer.parseInt(curX2);
        board.curY2 = Integer.parseInt(curY2);
        board.shapeOrder = Integer.parseInt(shapeOrder2);
        

    }// </editor-fold>
}
